<template>
  <div class="mt-md">
    <a-form ref="formRef" :model="formState" :wrapper-col="{ span: 24 }">
      <a-form-item v-bind="validateInfos.username">
        <a-input
          size="large"
          placeholder="请输入用户名"
          icon="UserOutlined"
          name="username"
          v-model:value="formState.username"
        >
          <template #prefix>
            <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item v-bind="validateInfos.password">
        <a-input-password
          v-model:value="formState.password"
          size="large"
          autocomplete
          name="password"
          placeholder="请输入密码"
        >
          <template #prefix>
            <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-button :loading="loading" size="large" @click="onSubmit" type="primary" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { useForm } from '@ant-design-vue/use'
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { defineComponent, reactive, ref, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import store from '../../store'
import { Login } from '../../store/modules/user/actionCreators'

export default defineComponent({
  name: 'LoginForm',
  components: {
    UserOutlined,
    LockOutlined
  },
  setup() {
    const formRef = ref()
    const formState = reactive({ username: '', password: '' })
    const rulesRef = reactive({
      username: [{ required: true, message: '用户名不能为空' }],
      password: [{ required: true, message: '密码不能为空' }]
    })

    const { resetFields, validate, validateInfos } = useForm(formState, rulesRef)
    const router = useRouter()
    const onSubmit = async () => {
      await validate()
      await store.dispatch(Login(toRaw(formState).username, toRaw(formState).password))
      router.push('/')
      // console.log(toRaw(formState))
    }

    return {
      resetFields,
      onSubmit,
      validateInfos,
      formRef,
      formState,
      loading: ref(false)
    }
  }
})
</script>

<style scoped></style>
